import path from "node:path";
import fs from "fs-extra";
import UniApp from "@dcloudio/vite-plugin-uni";
import UniComponents from "@uni-helper/vite-plugin-uni-components";
import AutoImport from "unplugin-auto-import/vite";
import { defineConfig } from "vite";
import { NutResolver } from "nutui-uniapp";
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from "weapp-tailwindcss/vite";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";

function r(...paths: string[]) {
  return path.resolve(process.cwd(), ".", ...paths);
}

const isH5 = process.env.UNI_PLATFORM === "h5";
const isApp = process.env.UNI_PLATFORM === "app";
const WeappTailwindcssDisabled = isH5 || isApp;

const resolve = (p) => {
  return path.resolve(__dirname, p);
};

export default defineConfig({
  resolve: {
    alias: {
      "@": r("src"),
    },
  },
  plugins: [
    UniComponents({
      resolvers: [NutResolver()],
    }),
    AutoImport({
      imports: [
        "vue",
        {
          "nutui-uniapp/composables": [
            // 在这里添加需要自动导入的API
            "useToast",
          ],
        },
      ],
    }),
    UniApp.default(),
    uvwt({
      rem2rpx: true,
      disabled: WeappTailwindcssDisabled,
      // 由于 hbuilderx 会改变 process.cwd 所以这里必须传入当前目录的绝对路径
      tailwindcssBasedir: __dirname,
    }),
  ],
  css: {
    postcss: {
      plugins: [tailwindcss(resolve("./tailwind.config.js")), autoprefixer],
    },
  },
});
